jQuery(document).ready(function ($) {
    // 多语切换
    var multiLang = localStorage.getItem('multiLang') || 'zh-CN';
    var multiLangs = ['co', 'gn', 'rw', 'ha', 'no', 'af', 'yo', 'en', 'gom', 'la', 'ne', 'fr', 'cs', 'haw', 'ka', 'ru', 'zh-CN', 'fa', 'bho', 'hi', 'be', 'sw', 'is', 'yi', 'ak', 'ga', 'gu', 'km', 'sk', 'iw', 'kn', 'hu', 'ta', 'ar', 'bn', 'az', 'sm', 'su', 'da', 'sn', 'bm', 'lt', 'vi', 'mt', 'tk', 'as', 'ca', 'si', 'ceb', 'gd', 'sa', 'pl', 'gl', 'lv', 'uk', 'tt', 'cy', 'ja', 'tl', 'ay', 'lo', 'te', 'ro', 'ht', 'doi', 'sv', 'mai', 'th', 'hy', 'my', 'ps', 'hmn', 'dv', 'zh-TW', 'lb', 'sd', 'ku', 'tr', 'mk', 'bg', 'ms', 'lg', 'mr', 'et', 'ml', 'de', 'sl', 'ur', 'pt', 'ig', 'ckb', 'om', 'el', 'es', 'fy', 'so', 'am', 'ny', 'pa', 'eu', 'it', 'sq', 'ko', 'tg', 'fi', 'ky', 'ee', 'hr', 'qu', 'bs', 'mi', 'or', 'ti', 'kk', 'nl', 'kri', 'ln', 'mg', 'mn', 'lus', 'xh', 'zu', 'sr', 'nso', 'st', 'eo', 'mni-Mtei', 'ug', 'uz', 'ilo', 'id', 'jw', 'ts'];
    if (multiLang && multiLangs.indexOf(multiLang) !== -1 && _localize.lang != multiLang) {
        window.location.href = window.location.href.replace('/' + _localize.lang + '/', '/').replace(_localize.site_url, _localize.site_url + (multiLang === 'zh-CN' ? '' : '/' + multiLang));
    }
    $('.dropdown-language>li, .select-language>a, #selectLanguage>option').click(function () {
        var slug = $(this).data('slug');
        localStorage.setItem('multiLang', slug);
        setTimeout(function () {
            window.location.href = window.location.href.replace('/' + _localize.lang + '/', '/').replace(_localize.site_url, _localize.site_url + (slug === 'zh-CN' ? '' : '/' + slug));
        });
    });

    // 代码高亮
    if ($('.entry-content').length) {
        $('.entry-content p:first').addClass('lead');
        $('.entry-content').css('font-size', '16px');
        $('.entry-content pre').addClass('prettyprint linenums');
        window.prettyPrint && window.prettyPrint();
        $('.entry-content pre.prettyprint ol.linenums>li').attr('style', 'list-style-type: decimal;white-space: pre-wrap');
    }

    // 模态框
    var loginArr = [];
    var registerArr = [];
    loginArr.push('<div class="modal fade bs-modal-login" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">\n');
    loginArr.push('\t<div class="modal-dialog modal-sm" role="document">\n');
    loginArr.push('\t\t<div class="modal-content">\n');
    loginArr.push('\t\t\t<div class="modal-header">\n');
    loginArr.push('\t\t\t\t<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>\n');
    loginArr.push('\t\t\t\t<h4 class="modal-title">' + _localize.login + ' <small><a class="register" href="javascript:;" rel="nofollow" title="' + _localize.switch_register + '">' + _localize.switch_register + '</a></small></h4>\n');
    loginArr.push('\t\t\t</div>\n');
    loginArr.push('\t\t\t<div class="modal-body">\n');
    loginArr.push('\t\t\t\t<form id="loginForm" style="height: 220px;">\n');
    loginArr.push('\t\t\t\t\t<div class="form-group">\n');
    loginArr.push('\t\t\t\t\t\t<label for="inputUsername">' + _localize.username + '</label>\n');
    loginArr.push('\t\t\t\t\t\t<input type="text" class="form-control" name="username" value="anonymous" id="inputUsername" placeholder="' + _localize.input_username + '" />\n');
    loginArr.push('\t\t\t\t\t</div>\n');
    loginArr.push('\t\t\t\t\t<div class="form-group">\n');
    loginArr.push('\t\t\t\t\t\t<label for="inputPasswrod">' + _localize.password + '</label>\n');
    loginArr.push('\t\t\t\t\t\t<input type="password" class="form-control" name="password" value="123456" id="inputPasswrod" placeholder="' + _localize.input_password + '" />\n');
    loginArr.push('\t\t\t\t\t</div>\n');
    loginArr.push('\t\t\t\t\t<div class="checkbox">\n');
    loginArr.push('\t\t\t\t\t\t<label>\n');
    loginArr.push('\t\t\t\t\t\t\t<input type="hidden" name="remember" value="0" />\n');
    loginArr.push('\t\t\t\t\t\t\t<input type="checkbox" name="remember" value="1" checked /> ' + _localize.remember_me + '\n');
    loginArr.push('\t\t\t\t\t\t</label>\n');
    loginArr.push('\t\t\t\t\t</div>\n');
    loginArr.push('\t\t\t\t\t<div class="form-group" style="position: relative;">\n');
    loginArr.push('\t\t\t\t\t\t<button type="submit" class="btn btn-primary pull-right">' + _localize.login + '</button>\n');
    loginArr.push('\t\t\t\t\t\t<span class="tips"></span>\n');
    loginArr.push('\t\t\t\t\t</div>\n');
    loginArr.push('\t\t\t\t</form>\n');
    loginArr.push('\t\t\t</div>\n');
    loginArr.push('\t\t</div>\n');
    loginArr.push('\t</div>\n');
    loginArr.push('</div>\n');
    registerArr.push('<div class="modal fade bs-modal-register" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">\n');
    registerArr.push('\t<div class="modal-dialog modal-sm" role="document">\n');
    registerArr.push('\t\t<div class="modal-content">\n');
    registerArr.push('\t\t\t<div class="modal-header">\n');
    registerArr.push('\t\t\t\t<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>\n');
    registerArr.push('\t\t\t\t<h4 class="modal-title">' + _localize.register + ' <small><a class="login" href="javascript:;" rel="nofollow" title="' + _localize.switch_login + '">' + _localize.switch_login + '</a></small></h4>\n');
    registerArr.push('\t\t\t</div>\n');
    registerArr.push('\t\t\t<div class="modal-body">\n');
    registerArr.push('\t\t\t\t<form id="registerForm" style="height: 440px;">\n');
    registerArr.push('\t\t\t\t\t<div class="form-group">\n');
    registerArr.push('\t\t\t\t\t\t<label for="inputRegUsername">' + _localize.username + '</label>\n');
    registerArr.push('\t\t\t\t\t\t<input type="text" class="form-control" name="username" value="" id="inputRegUsername" placeholder="' + _localize.input_username + '" />\n');
    registerArr.push('\t\t\t\t\t</div>\n');
    registerArr.push('\t\t\t\t\t<div class="form-group">\n');
    registerArr.push('\t\t\t\t\t\t<label for="inputRegPasswrod">' + _localize.password + '</label>\n');
    registerArr.push('\t\t\t\t\t\t<input type="password" class="form-control" name="password" value="" id="inputRegPasswrod" placeholder="' + _localize.input_password + '" />\n');
    registerArr.push('\t\t\t\t\t</div>\n');
    registerArr.push('\t\t\t\t\t<div class="form-group">\n');
    registerArr.push('\t\t\t\t\t\t<label for="inputRegRepeatPassword">' + _localize.repeat_password + '</label>\n');
    registerArr.push('\t\t\t\t\t\t<input type="password" class="form-control" name="repeat_password" value="" id="inputRegRepeatPassword" placeholder="' + _localize.input_repeat_password + '" />\n');
    registerArr.push('\t\t\t\t\t</div>\n');
    registerArr.push('\t\t\t\t\t<div class="form-group">\n');
    registerArr.push('\t\t\t\t\t\t<label for="inputRegNickname">' + _localize.nickname + '</label>\n');
    registerArr.push('\t\t\t\t\t\t<input type="text" class="form-control" name="nickname" value="" id="inputRegNickname" placeholder="' + _localize.optional + '" />\n');
    registerArr.push('\t\t\t\t\t</div>\n');
    registerArr.push('\t\t\t\t\t<div class="form-group">\n');
    registerArr.push('\t\t\t\t\t\t<label for="inputRegPhone">' + _localize.phone + '</label>\n');
    registerArr.push('\t\t\t\t\t\t<input type="text" class="form-control" name="phone" value="" id="inputRegPhone" placeholder="' + _localize.optional + '" />\n');
    registerArr.push('\t\t\t\t\t</div>\n');
    registerArr.push('\t\t\t\t\t<div class="checkbox">\n');
    registerArr.push('\t\t\t\t\t\t<label>\n');
    registerArr.push('\t\t\t\t\t\t\t<input type="hidden" name="remember" value="0" />\n');
    registerArr.push('\t\t\t\t\t\t\t<input type="checkbox" name="remember" value="1" checked /> ' + _localize.remember_me + '\n');
    registerArr.push('\t\t\t\t\t\t</label>\n');
    registerArr.push('\t\t\t\t\t</div>\n');
    registerArr.push('\t\t\t\t\t<div class="form-group" style="position: relative;">\n');
    registerArr.push('\t\t\t\t\t\t<button type="submit" class="btn btn-primary pull-right">' + _localize.register + '</button>\n');
    registerArr.push('\t\t\t\t\t\t<span class="tips"></span>\n');
    registerArr.push('\t\t\t\t\t</div>\n');
    registerArr.push('\t\t\t\t</form>\n');
    registerArr.push('\t\t\t</div>\n');
    registerArr.push('\t\t</div>\n');
    registerArr.push('\t</div>\n');
    registerArr.push('</div>\n');

    // 登录
    $('body').on('click', '.login', function () {
        $.post(_localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/islogin.html', function(res) {
            if (res.code) return alertBox(res.msg);
            $('.bs-modal-login').remove();
            $('body').append(loginArr.join(''));
            $('.bs-modal-register').modal('hide');
            $('.bs-modal-login').modal('show');
        }, 'json');
    });
    $('body').on('submit', '#loginForm', function (e) {
        e.preventDefault();
        $('#loginForm .tips').html('<span class="glyphicon glyphicon-refresh" style="animation: turn-around 1.5s linear infinite;" aria-hidden="true"></span> ' + _localize.logining + '...');
        $.post(_localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/login.html', $('#loginForm').serialize(), function (res) {
            if (res.code) return $('#loginForm .tips').html('<span class="glyphicon glyphicon-remove" aria-hidden="true"></span> ' + res.msg);
            $('#loginForm .tips').html('<span class="glyphicon glyphicon-ok" aria-hidden="true"></span> ' + res.msg + '，' + _localize.redirecting + '...');
            if (undefined !== res.token) localStorage.setItem('webToken', res.token);
            setTimeout(function () {
                if (self.frameElement && self.frameElement.tagName == 'IFRAME') {
                    parent.window.location.reload();
                } else {
                    window.location.reload();
                }
            }, 1000);
        }, 'json');
    });

    // 注册
    $('body').on('click', '.register', function () {
        $.post(_localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/islogin.html', function(res) {
            if (res.code) return alertBox(res.msg);
            $('.bs-modal-register').remove();
            $('body').append(registerArr.join(''));
            $('.bs-modal-login').modal('hide');
            $('.bs-modal-register').modal('show');
        }, 'json');
    });
    $('body').on('submit', '#registerForm', function (e) {
        e.preventDefault();
        $('#registerForm .tips').html('<span class="glyphicon glyphicon-refresh" style="animation: turn-around 1.5s linear infinite;" aria-hidden="true"></span> ' + _localize.registering + '...');
        $.post(_localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/register.html', $('#registerForm').serialize(), function (res) {
            if (res.code) return $('#registerForm .tips').html('<span class="glyphicon glyphicon-remove" aria-hidden="true"></span> ' + res.msg);
            $('#registerForm .tips').html('<span class="glyphicon glyphicon-ok" aria-hidden="true"></span> ' + res.msg + '，' + _localize.redirecting + '...');
            if (undefined !== res.token) localStorage.setItem('webToken', res.token);
            setTimeout(function () {
                if (self.frameElement && self.frameElement.tagName == 'IFRAME') {
                    parent.window.location.reload();
                } else {
                    window.location.reload();
                }
            }, 1000);
        }, 'json');
    });

    // 登出
    $('body').on('click', '.logout', function (e) {
        $.post(_localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/logout.html', function (res) {
            if (res.code) return alertBox(res.msg);
            if (undefined !== res.token) localStorage.removeItem('webToken');
            alertBox(res.msg);
            setTimeout(function () {
                if (self.frameElement && self.frameElement.tagName == 'IFRAME') {
                    parent.window.location.reload();
                } else {
                    window.location.reload();
                }
            }, 1000);
        }, 'json');
    });

    // 模态弹出框
    function alertBox(msg, title) {
        var arr = [];
        arr.push('<div class="modal fade bs-modal-alert" tabindex="-1" role="dialog">\n')
        arr.push('\t<div class="modal-dialog modal-sm" role="document">\n');
        arr.push('\t\t<div class="modal-content">\n');
        arr.push('\t\t\t<div class="modal-header">\n');
        arr.push('\t\t\t\t<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>\n');
        arr.push('\t\t\t\t<h4 class="modal-title">' + (title ? title : _localize.info) + '</h4>\n');
        arr.push('\t\t\t</div>\n');
        arr.push('\t\t\t<div class="modal-body">' + msg + '</div>\n');
        arr.push('\t\t\t<div class="modal-footer">\n');
        arr.push('\t\t\t\t<button type="button" class="btn btn-default" data-dismiss="modal">' + _localize.sure + '</button>\n');
        arr.push('\t\t\t</div>\n');
        arr.push('\t\t</div>\n');
        arr.push('\t</div>\n');
        arr.push('</div>\n');
        $('.bs-modal-alert').modal('hide');
        $('.bs-modal-alert').remove();
        $('body').append(arr.join(''));
        $('.bs-modal-alert').modal('show');
    }

    // 点击数更新
    if ($('.post-views').length) {
        var views = parseInt(_localize.article_views);
        var store = [];
        try {
            store = JSON.parse(localStorage.getItem('multiPostViews') || '[]');
        } catch (e) {
            localStorage.removeItem('multiPostViews');
            store = [];
        }
        // var obj = store.find(function (item) {
        //     return item.id == _localize.article_id;
        // });
        // 兼容IE10
        var obj = null;
        for (var i = 0; i < store.length; i++) {
            if (store[i].id == _localize.article_id) {
                obj = store[i];
            }
        }
        if (obj) {
            // 拒绝2小时内恶意刷新
            if (+new Date() - obj.timestamp >= 2 * 3600 * 1000) {
                obj.views = views + 1;
                obj.timestamp = +new Date();
                obj.lang = _localize.lang;
                localStorage.setItem('multiPostViews', JSON.stringify(store));
                $.post(_localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/views.html', { id: _localize.article_id, views: views }, 'json');
            }
            $('.post-views').html(obj.views);
        } else {
            // 首次执行
            store.push({ id: _localize.article_id, views: views + 1, timestamp: +new Date(), lang: _localize.lang });
            localStorage.setItem('multiPostViews', JSON.stringify(store));
            $('.post-views').html(views + 1);
            $.post(_localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/views.html', { id: _localize.article_id, views: views }, 'json');
        }
    }

    // 下载内容
    if ($('.entry-content').length) {
        $('body').on('click', '.btn-download', function () {
            var _this = this;
            $.ajax({
                type: 'POST',
                url: _localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/download.html',
                data: {
                    post_id: _localize.article_id,
                },
                dataType: 'json',
                cache: false,
                beforeSend: function () {
                    $(_this).attr('disabled', 'disabled').removeClass('btn-download');
                    $(_this).parent().next('.btn-group').next('.loading').remove();
                    $(_this).parent().next('.btn-group').after('<div class="text-muted loading" style="margin-top:10px"><img src="' + _localize.site_url + '/static/images/loading.gif" alt="Loading"> ' + _localize.merging + '...</div>');
                },
                success: function (res) {
                    if (res.code) {
                        $(_this).removeAttr('disabled').addClass('btn-download');
                        $(_this).parent().next('.btn-group').next('.loading').removeClass('text-muted').addClass('text-danger').html('<span class="glyphicon glyphicon-remove"></span> ' + res.msg);
                    } else {
                        $(_this).removeAttr('disabled').removeClass('btn-download').attr('href', res.link).attr('download', 'ID' + (Array(7).join('0') + _localize.article_id).slice(-7) + '-' + _localize.lang + '-' + res.msg + '.html');
                        $(_this).parent().next('.btn-group').next('.loading').removeClass('text-muted').addClass('text-success').html('<span class="glyphicon glyphicon-ok"></span> ' + _localize.merge_success);
                    }
                    setTimeout(function () {
                        $(_this).parent().next('.btn-group').next('.loading').remove();
                    }, 5000);
                },
                error: function (response) {
                    $(_this).removeAttr('disabled').addClass('btn-download');
                    $(_this).parent().next('.btn-group').next('.loading').removeClass('text-muted').addClass('text-warning').html('<span class="glyphicon glyphicon-alert"></span> Error! ' + response.statusText + ' ' + response.status);
                    setTimeout(function () {
                        $(_this).parent().next('.btn-group').next('.loading').remove();
                    }, 3000);
                }
            });
        });
    }

    // 收藏文章
    if ($('.entry-content').length) {
        var store = [];
        try {
            store = JSON.parse(localStorage.getItem('multiPostFavorites') || '[]');
        } catch (e) {
            localStorage.removeItem('multiPostFavorites');
            store = [];
        }
        // var obj = store.find(function (item) {
        //     return item.id == _localize.article_id;
        // });
        // 兼容IE10
        var obj = null;
        for (var i = 0; i < store.length; i++) {
            if (store[i].id == _localize.article_id) {
                obj = store[i];
            }
        }
        if (obj) {
            $('.btn-favorite').removeClass('btn-warning').attr('title', _localize.favorite_cancel).html('<span class="glyphicon glyphicon-star" aria-hidden="true"></span> ' + _localize.favorite_success);
        } else {
            $('.btn-favorite').addClass('btn-warning').attr('title', _localize.favorite_article).html('<span class="glyphicon glyphicon-star-empty" aria-hidden="true"></span> ' + _localize.favorite_article);
        }
        $('.btn-favorite').click(function () {
            var store = [];
            try {
                store = JSON.parse(localStorage.getItem('multiPostFavorites') || '[]');
            } catch (e) {
                localStorage.removeItem('multiPostFavorites');
                store = [];
            }
            // var obj = store.find(function (item) {
            //     return item.id == _localize.article_id;
            // });
            // 兼容IE10
            var obj = null;
            for (var i = 0; i < store.length; i++) {
                if (store[i].id == _localize.article_id) {
                    obj = store[i];
                }
            }
            if (!obj && $(this).hasClass('btn-warning')) {
                $(this).removeClass('btn-warning').attr('title', _localize.favorite_cancel).html('<span class="glyphicon glyphicon-star" aria-hidden="true"></span> ' + _localize.favorite_success);
                store.unshift({ id: _localize.article_id, timestamp: +new Date(), lang: _localize.lang });
            } else {
                $(this).addClass('btn-warning').attr('title', _localize.favorite_article).html('<span class="glyphicon glyphicon-star-empty" aria-hidden="true"></span> ' + _localize.favorite_article);
                // var index = store.findIndex(function (item) {
                //     return item.id == _localize.article_id;
                // });
                // store.splice(index, 1);
                // 兼容IE10
                var newArr = [];
                for (var i = 0; i < store.length; i++) {
                    if (store[i].id == _localize.article_id)
                        continue;
                    newArr.push(store[i]);
                }
                store = newArr;
            }
            localStorage.setItem('multiPostFavorites', JSON.stringify(store));
            $('.panel-pages .list-group a[data-slug="page-favorites"]').find('.badge').text(store.length);
        });
    }

    // 点赞
    if ($('.post-likes').length) {
        var likes = parseInt(_localize.article_likes);
        var store = [];
        try {
            store = JSON.parse(localStorage.getItem('multiPostLikes') || '[]');
        } catch (e) {
            localStorage.removeItem('multiPostLikes');
            store = [];
        }
        // var obj = store.find(function (item) {
        //     return item.id == _localize.article_id;
        // });
        // 兼容IE10
        var obj = null;
        for (var i = 0; i < store.length; i++) {
            if (store[i].id == _localize.article_id) {
                obj = store[i];
            }
        }
        if (obj) {
            $('.btn-likes').addClass('disabled').addClass('btn-disabled');
        }
        $('.btn-likes').click(function () {
            if ($(this).hasClass('disabled') || $(this).hasClass('btn-disabled'))
                return;
            $(this).addClass('disabled').addClass('btn-disabled');
            store.unshift({ id: _localize.article_id, likes: likes + 1, timestamp: +new Date(), lang: _localize.lang });
            localStorage.setItem('multiPostLikes', JSON.stringify(store));
            $('.post-likes').html(likes + 1);
            $.post(_localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/likes.html', { id: _localize.article_id, likes: likes }, 'json');
            $('.panel-pages .list-group a[data-slug="page-likes"]').find('.badge').text(store.length);
        });
    }

    // 更新点赞收藏文章数量
    if ($('.panel-pages').length) {
        var favorites = [];
        try {
            favorites = JSON.parse(localStorage.getItem('multiPostFavorites') || '[]');
        } catch (e) {
            localStorage.removeItem('multiPostFavorites');
            favorites = [];
        }
        var likes = [];
        try {
            likes = JSON.parse(localStorage.getItem('multiPostLikes') || '[]');
        } catch (e) {
            localStorage.removeItem('multiPostLikes');
            likes = [];
        }
        // var findFavorites = favorites.filter(function (item) {
        //     return item.lang == _localize.lang;
        // });
        // var findLikes = likes.filter(function (item) {
        //     return item.lang == _localize.lang;
        // });
        // 兼容IE10
        var findFavorites = [];
        for (var i = 0; i < favorites.length; i++) {
            if (favorites[i].lang == _localize.lang) {
                findFavorites.push(favorites[i]);
            }
        }
        var findLikes = [];
        for (var i = 0; i < likes.length; i++) {
            if (likes[i].lang == _localize.lang) {
                findLikes.push(likes[i]);
            }
        }
        $('#page-favorites').text(findFavorites.length);
        $('#page-likes').text(findLikes.length);
        $('.panel-pages .list-group .list-group-item').each(function (i, elem) {
            $(elem).data('slug') == 'page-favorites' && $(elem).find('.badge').text(findFavorites.length);
            $(elem).data('slug') == 'page-likes' && $(elem).find('.badge').text(findLikes.length);
        });
    }

    // 获取收藏点赞文章列表
    if ($('#page-lists').length) {
        var slug = $('#page-lists').data('slug');
        var p = 1;
        var url_part = location.href.slice(location.href.lastIndexOf('/') + 1);
        var match = url_part.match(/^page-(\d+).html/);
        if (match) p = match[1];
        var storeName = slug == 'page-favorites' ? 'multiPostFavorites' : (slug == 'page-likes' ? 'multiPostLikes' : '');
        if (storeName == '') return false;
        var store = [];
        try {
            store = JSON.parse(localStorage.getItem(storeName) || '[]');
        } catch (e) {
            localStorage.removeItem(storeName);
            store = [];
        }
        // store = store.filter(function (item) {
        //     return item.lang == _localize.lang;
        // });
        // var ids = store.map(function (item) {
        //     return item.id;
        // });
        // 兼容IE10
        var ids = [];
        var newArr = [];
        for (var i = 0; i < store.length; i++) {
            if (store[i].lang == _localize.lang) {
                ids.push(store[i].id);
                newArr.push(store[i]);
            }
        }
        store = newArr;
        $.ajax({
            type: 'POST',
            url: _localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/page_lists.html',
            data: {
                ids: ids,
                p: p,
                slug: slug,
            },
            dataType: 'json',
            cache: false,
            beforeSend: function () {
                $('<div id="loading" class="text-center"><i class="icon-loading"></i> Loading...</div>').appendTo('#page-lists');
            },
            success: function (res) {
                if (res.code) {
                    $('#page-lists #loading').html(res.msg)
                    setTimeout(function () {
                        $('#page-lists #loading').html('').remove();
                    }, 3000);
                    return false;
                }
                $('#page-lists #loading').html('').remove();
                $('#page-counts').text(res.count);
                var list = JSON.parse(res.data || '[]');
                for (var i in list) {
                    $(list[i]).appendTo('#page-lists');
                }
                res.count && $(res.pager).appendTo('#page-lists');
                lazyLoad();
            },
            error: function (XMLHttpRequest, textStatus) {
                $('#page-lists #loading').html(textStatus + ': ' + XMLHttpRequest.status);
                setTimeout(function () {
                    $('#page-lists #loading').html('').remove();
                }, 3000);
            }
        });
    }

    // 语音播报
    if ($('.entry-content').length && _localize.voice_read == '1') {
        var stopped = true;
        var audio = new Audio();
        var audioArray = [];
        var textArray = [];
        var nodes = [];
        var speechInstance = null;
        var offLine = false;
        var api = '';
        var ignore = ['STYLE', 'SCRIPT', 'IFRAME', 'VIDEO', 'AUDIO', 'SOURCE', 'PRE', 'CODE', 'IMG', 'BR', 'HR', 'TABLE', 'FORM', 'FIELDSET', 'LEGEND', 'LABEL', 'INPUT', 'TEXTAREA', 'SELECT', 'BUTTON'];
        var playErrors = 0;
        var playErrorTimer = null;
        $('<meta name="referrer" content="same-origin">').appendTo('head').remove();
        $('.entry-content').contents().each(function (i, node) {
            if (ignore.indexOf(node.tagName) === -1 && node.textContent.trim()) {
                nodes.push({ node: node, index: i });
            }
        });
        if ('speechSynthesis' in window) {
            var i = 0;
            var timer = setInterval(function () {
                i++;
                var voices = window.speechSynthesis.getVoices();
                if (voices.length || i > 10) {
                    clearInterval(timer);
                    for (var j = 0; j < voices.length; j++) {
                        if (voices[j].lang.indexOf(_localize.lang) !== -1) {
                            offLine = voices[j].lang;
                            break;
                        }
                    }
                }
            }, 100);
        }
        function playEndedHandler() {
            playErrors = 0;
            if (textArray.length > 0) {
                if (!offLine) {
                    audio.src = audioArray.pop();
                    audio.play();
                }
                var reader = textArray.shift();
                if (offLine) {
                    speechInstance.text = reader.text;
                    window.speechSynthesis.speak(speechInstance);
                }
                var elem = null;
                for (var i = 0; i < nodes.length; i++) {
                    if (reader.index == nodes[i].index) {
                        if (nodes[i].node.nodeType === 3) {
                            var wrapper = document.createElement('span');
                            nodes[i].node.parentNode.insertBefore(wrapper, nodes[i].node);
                            nodes[i].node.parentNode.removeChild(nodes[i].node);
                            wrapper.appendChild(nodes[i].node);
                            nodes[i].node = wrapper;
                        }
                        elem = nodes[i].node;
                        $(nodes[i].node).addClass('tts');
                    } else {
                        if (nodes[i].node.nodeType === 1) {
                            $(nodes[i].node).removeClass('tts');
                        }
                    }
                }
                var clientHeight = $(window).height();
                var scrollTop = $(window).scrollTop();
                var pos = $(elem).offset().top;
                var topH = $(elem).height();
                if (pos > clientHeight + scrollTop - topH) {
                    $('html, body').stop().animate({
                        scrollTop: pos - 10
                    });
                }
            } else {
                stop();
                setTimeout(function () {
                    $('html, body').stop().animate({
                        scrollTop: 0
                    });
                }, 1000);
            }
        }
        function playErrorHandler() {
            playErrorTimer && clearTimeout(playErrorTimer);
            playErrorTimer = setTimeout(function () {
                if (playErrors % 10 < 9) {
                    playErrors++;
                    audio.src = audio.src.split('&t=')[0] + '&t=' + new Date().getTime();
                    audio.play();
                } else {
                    clearTimeout(playErrorTimer);
                    playErrorTimer = null;
                    playErrors = 0;
                    stop();
                    $('#loading').html('<div class="text-warning"><span class="glyphicon glyphicon-alert"></span> Error! Audio error code: ' + audio.error.code + '</div>');
                }
            }, 3000 + Math.ceil(Math.random() * 2000));
        }
        function play() {
            $('.fixed-bottom .play-btn').removeClass('play-btn').addClass('pause-btn').html('<span class="glyphicon glyphicon-pause" aria-hidden="true"></span>');
            $('.btn-group .btn-play').next('.btn-stop').remove();
            $('.btn-group .btn-play').after('<button type="button" class="btn btn-default btn-stop" aria-label="Left Align"><span class="glyphicon glyphicon-stop" aria-hidden="true"></span></button>');
            $('.btn-group .btn-play').removeClass('btn-play').addClass('btn-pause').html('<span class="glyphicon glyphicon-pause" aria-hidden="true"></span>');
            if (stopped) {
                if (nodes.length < 1) {
                    return false;
                }
                $('#loading').html('<span class="icon-loading"></span> ' + _localize.waiting + ' ...');
                var icon = new Image();
                icon.src = 'https://translate.google.com/favicon.ico?t=' + new Date().getTime();
                var timer = setTimeout(function () {
                    icon.onerror = icon.onload = null;
                    youdao_dictvoice();
                }, 3000);
                icon.onerror = function () {
                    clearTimeout(timer);
                    timer = null;
                    youdao_dictvoice();
                }
                icon.onload = function () {
                    clearTimeout(timer);
                    timer = null;
                    google_translate_tts();
                }
                function google_translate_tts() {
                    offLine = false;
                    api = 'https://translate.google.com/translate_tts?client=webapp&ie=UTF-8&oe=UTF-8&tl=' + (_localize.voice ? _localize.voice : _localize.lang) + '&q=';
                    doPlay();
                }
                function youdao_dictvoice() {
                    var icon = new Image();
                    icon.src = 'https://dict.youdao.com/favicon.ico?t=' + new Date().getTime();
                    var timer = setTimeout(function () {
                        icon.onerror = icon.onload = null;
                        if (offLine) {
                            doPlay();
                        } else {
                            stop();
                            $('#loading').html('<div class="text-warning"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> ' + _localize.voice_read_error + ' ...</div>');
                        }
                    }, 3000);
                    icon.onerror = function () {
                        clearTimeout(timer);
                        timer = null;
                        if (offLine) {
                            doPlay();
                        } else {
                            stop();
                            $('#loading').html('<div class="text-warning"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> ' + _localize.voice_read_error + ' ...</div>');
                        }
                    }
                    icon.onload = function () {
                        clearTimeout(timer);
                        timer = null;
                        if (['ar', 'de', 'ru', 'fr', 'ko', 'nl', 'pt', 'ja', 'th', 'es', 'en', 'it', 'vi', 'id'].indexOf(_localize.lang) !== -1 || _localize.lang.match(/^zh-/)) {
                            offLine = false;
                            api = 'https://dict.youdao.com/dictvoice?le=' + (_localize.lang.match(/^zh-/) ? 'zh-CHS' : _localize.lang) + '&product=aibox&audio=';
                            doPlay();
                        } else {
                            $('#loading').html('<div class="text-warning"><span class="glyphicon glyphicon-alert"></span> ' + _localize.voice_not_support + '</div>');
                            $('.btn-group .btn-play').attr('disabled', true);
                        }
                    }
                }
                function doPlay() {
                    var num = 200;
                    for (var i = 0; i < nodes.length; i++) {
                        var arrs = $(nodes[i].node).text().trim().split(/(\r\n|\r|\n)/g);
                        for (var j = 0; j < arrs.length; j++) {
                            var aAudioText = arrs[j].trim();
                            if (aAudioText && !offLine) {
                                while (aAudioText.length >= num) {
                                    var arr = [];
                                    for (var k in aAudioText) {
                                        arr.push(aAudioText[k]);
                                        if (arr.join('').length >= num) {
                                            arr.pop();
                                            break;
                                        }
                                    }
                                    var pos = arr.join('').length;
                                    textArray.push({ text: aAudioText.slice(0, pos), index: nodes[i].index });
                                    aAudioText = aAudioText.slice(pos);
                                }
                            }
                            aAudioText && textArray.push({ text: aAudioText, index: nodes[i].index });
                        }
                    }
                    if (textArray.length < 1) {
                        return false;
                    }
                    if (!offLine) {
                        for (var i = 0; i < textArray.length; i++) {
                            var address = api + encodeURIComponent(textArray[i].text);
                            if (api.match(/\/\/[\w]+\.google/)) {
                                address += '&tk=' + getTk(textArray[i].text);
                            }
                            audioArray.unshift(address);
                        }
                        audio.preload = true;
                        audio.controls = true;
                        audio.src = audioArray.pop();
                        audio.addEventListener('ended', playEndedHandler);
                        audio.addEventListener('error', playErrorHandler);
                        audio.loop = false;
                        audio.play();
                    }
                    stopped = false;
                    var reader = textArray.shift();
                    if (offLine) {
                        speechInstance = new SpeechSynthesisUtterance();
                        window.speechSynthesis.cancel();
                        speechInstance.lang = offLine;
                        speechInstance.text = reader.text;
                        window.speechSynthesis.speak(speechInstance);
                        speechInstance.addEventListener('end', playEndedHandler);
                    }
                    for (var i = 0; i < nodes.length; i++) {
                        if (reader.index == nodes[i].index) {
                            if (nodes[i].node.nodeType === 3) {
                                var wrapper = document.createElement('span');
                                nodes[i].node.parentNode.insertBefore(wrapper, nodes[i].node);
                                nodes[i].node.parentNode.removeChild(nodes[i].node);
                                wrapper.appendChild(nodes[i].node);
                                nodes[i].node = wrapper;
                            }
                            $(nodes[i].node).addClass('tts');
                        } else {
                            if (nodes[i].node.nodeType === 1) {
                                $(nodes[i].node).removeClass('tts');
                            }
                        }
                    }
                    $('#loading').html('');
                }
            } else {
                if (!offLine) {
                    audio.play();
                } else {
                    window.speechSynthesis.resume();
                }
            }
        }
        function pause() {
            $('.fixed-bottom .pause-btn').removeClass('pause-btn').addClass('play-btn').html('<span class="glyphicon glyphicon-play" aria-hidden="true"></span>');
            $('.btn-group .btn-pause').removeClass('btn-pause').addClass('btn-play').html('<span class="glyphicon glyphicon-play" aria-hidden="true"></span>');
            if (!offLine) {
                audio.pause();
            } else {
                if (window.speechSynthesis.speaking) {
                    window.speechSynthesis.pause();
                }
            }
        }
        function stop() {
            $('.fixed-bottom .pause-btn').removeClass('pause-btn').addClass('play-btn').html('<span class="glyphicon glyphicon-play" aria-hidden="true"></span>');
            $('.btn-group .btn-stop').prev('.btn').removeClass('btn-pause').addClass('btn-play').html('<span class="glyphicon glyphicon-play" aria-hidden="true"></span>');
            $('.btn-group .btn-stop').remove();
            if (!offLine) {
                audio.pause();
                audio.removeEventListener('ended', playEndedHandler);
                audio.removeEventListener('error', playErrorHandler);
                audioArray = [];
            } else {
                window.speechSynthesis.cancel();
                speechInstance && speechInstance.removeEventListener('end', playEndedHandler);
            }
            stopped = true;
            textArray = [];
            for (var i = 0; i < nodes.length; i++) {
                if (nodes[i].node.nodeType === 1) {
                    $(nodes[i].node).removeClass('tts');
                }
            }
        }
        $('body').on('click', '.btn-group .btn-play', play);
        $('body').on('click', '.btn-group .btn-pause', pause);
        $('body').on('click', '.btn-group .btn-stop', stop);
    }

    // 更改字体大小
    $('body').on('click', '.btn-group .font-zoom', function () {
        var thisEle = $('.entry-content').css('font-size');
        var textFontSize = parseFloat(thisEle, 10);
        var unit = thisEle.slice(-2); //
        var cName = $(this).data('size');
        if (cName == 'bigger') {
            if (textFontSize <= 24) {
                textFontSize += 2;
            }
        } else if (cName == 'smaller') {
            if (textFontSize >= 14) {
                textFontSize -= 2;
            }
        }
        $('.entry-content').css('font-size', textFontSize + unit);
    });

    // 提交评论
    if ($('#comment-area #commentForm').length) {
        $('<input type="hidden" name="anti_spam" value="' + _localize.anti_spam_val + '">').prependTo($('#commentForm'));
    }
    $('#comment-area').on('submit', '#commentForm', function (e) {
        e.preventDefault();
        var type = $('#comment-area .btn-cancel-reply').length;
        $('#commentForm .tips').html('<span class="glyphicon glyphicon-refresh" style="animation: turn-around 1.5s linear infinite;" aria-hidden="true"></span> ' + _localize.submiting + '...');
        $('#commentForm button[type="submit"]').attr('disabled', true);
        $.ajax({
            url: _localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/comment.html',
            type: 'post',
            dataType: 'json',
            data: $('#commentForm').serialize(),
            success: function (res) {
                if (res.code) {
                    $('#commentForm .tips').html('<span class="glyphicon glyphicon-remove" aria-hidden="true"></span> ' + res.msg);
                    setTimeout(function () {
                        $('#commentForm button[type="submit"]').attr('disabled', false);
                        $('#commentForm .tips').html('');
                    }, 1000);
                    return false;
                }
                $('#commentForm .tips').html('<span class="glyphicon glyphicon-ok" aria-hidden="true"></span> ' + res.msg);
                var say = type ? res.data.nickname + ' ' + _localize.reply + '：' : '<strong>' + res.data.nickname + '</strong> <cite>' + _localize.say + '：</cite>';
                html = type ? '' : '<div class="panel panel-default" id="comment-' + res.data.id + '"><div class="panel-body">';
                html += '<div class="media" id="comment-' + res.data.id + '">';
                html += type ? '<hr style="margin-top: 10px;">' : '';
                html += '<div class="media-left">';
                html += '<img class="media-object img-circle avatar" style="width: 64px;height: 64px;background-color: #f1f1f1;" src="' + (res.data.avatar ? res.data.avatar : generateAvatar(res.data.nickname)) + '" alt="' + res.data.nickname + '">';
                html += '</div>';
                html += '<div class="media-body">';
                html += '<h4 class="media-heading">' + say + '</h4>';
                html += res.data.comment + (res.data.status != '0' ? ' [<span class="text-success">' + _localize.pending + '</span>]' : '');
                html += $('#commentForm input[name="can_delete"]').val() == '1' ? '（<a href="javascript:;" class="delete-comment text-danger" data-id="' + res.data.id + '" title="' + _localize.delete + '">' + _localize.delete + '</a>）' : '';
                html += type ? '' : '<div class="clearfix" style="margin: 10px 0;"><button type="button" data-id="' + res.data.id + '" class="pull-right btn btn-success btn-sm media-right btn-reply"><span class="glyphicon glyphicon-share-alt" aria-hidden="true"></span> ' + _localize.reply + '</button></div>';
                html += '</div>';
                html += '</div>';
                html += type ? '' : '</div></div>';
                $('#commentForm').after(html);
                $('#commentForm #comment').val(null);
                if (type) {
                    var obj = $('#commentForm').parent('.media-body');
                    var num = $('#commentForm').parent('.media-body').find('.media').length - 1;
                    if (num > 4) {
                        obj.find('.media').eq(5).addClass('hidden');
                        if (!obj.find('.pager').length) {
                            var str = '<nav aria-label="Page navigation">\n';
                            str += '<hr />\n';
                            str += '<ul class="pager" data-index="0">\n';
                            str += '<li class="disabled" data-type="prev"><a href="javascript:;">Previous</a></li>\n';
                            str += '<li data-type="next"><a href="javascript:;">Next</a></li>\n';
                            str += '<li data-type="all"><a href="javascript:;">All</a></li>\n';
                            str += '</ul>\n';
                            str += '</nav>\n';
                            obj.append(str);
                        }
                    } else {
                        obj.find('.pager').parent().remove();
                    }
                }
                $('#comment-area>.panel').length && $('#comment-area>.no-comment').remove();
                setTimeout(function () {
                    $('#commentForm .tips').html('');
                    $('#commentForm button[type="submit"]').attr('disabled', false);
                    $('#comment-area .btn-cancel-reply').trigger('click');
                }, 1000);
            },
            error: function (XMLHttpRequest, textStatus) {
                $('#commentForm .tips').html(textStatus + ': ' + XMLHttpRequest.status);
            }
        });
    });

    // 回复评论
    $('#comment-area').on('click', '.btn-reply', function () {
        $('#comment-area .btn-cancel-reply').removeClass('btn-cancel-reply').addClass('btn-reply').removeClass('btn-danger').addClass('btn-success').html('<span class="glyphicon glyphicon-share-alt" aria-hidden="true"></span> ' + _localize.reply);
        $(this).removeClass('btn-reply').addClass('btn-cancel-reply').removeClass('btn-success').addClass('btn-danger').html(_localize.cancel_reply).parent().after($('#commentForm'));
        $('#commentForm button[type="submit"]').html('@ ' + _localize.reply_comment);
        $('#commentForm').find('input[name="pid"]').val($(this).data('id'));
    });

    // 取消回复
    $('#comment-area').on('click', '.btn-cancel-reply', function () {
        $('#comment-area').prepend($('#commentForm')).find('.btn-cancel-reply').removeClass('btn-cancel-reply').addClass('btn-reply').removeClass('btn-danger').addClass('btn-success').html('<span class="glyphicon glyphicon-share-alt" aria-hidden="true"></span> ' + _localize.reply);
        $('#commentForm button[type="submit"]').html('<span class="glyphicon glyphicon-send" aria-hidden="true"></span> ' + _localize.send_comment);
        $('#commentForm').find('input[name="pid"]').val(0);
    });

    // 删除评论
    $('#comment-area').on('click', '.delete-comment', function () {
        if ($(this).parent().find('#commentForm').length) return;
        var comment_id = $(this).data('id');
        $.post(_localize.site_url + (_localize.lang == 'zh-CN' ? '' : '/' + _localize.lang) + '/ajax/delete_comment.html', { comment_id: comment_id }, function (res) {
            if (!res.code) {
                var item = $('#comment-area #comment-' + comment_id);
                var num = item.parent('.media-body').find('.media').length - 1;
                if (num > 5) {
                    if (!item.parent('.media-body').find('.pager').length) {
                        var str = '<nav aria-label="Page navigation">\n';
                        str += '<hr />\n';
                        str += '<ul class="pager" data-index="0">\n';
                        str += '<li class="disabled" data-type="prev"><a href="javascript:;" title="Previous">Previous</a></li>\n';
                        str += '<li data-type="next"><a href="javascript:;" title="Next">Next</a></li>\n';
                        str += '<li data-type="all"><a href="javascript:;" title="All">All</a></li>\n';
                        str += '</ul>\n';
                        str += '</nav>\n';
                        item.parent('.media-body').append(str);
                    }
                } else {
                    item.parent('.media-body').find('.pager').parent().remove();
                    item.parent('.media-body').find('.media').removeClass('hidden');
                }
                item.remove();
                !$('#comment-area>.panel').length && $('<p class="text-center text-muted no-comment">' + _localize.no_comment + '</p>').appendTo('#comment-area');
            }
        }, 'json');
    });

    // 回复评论分页
    $('#comment-area').on('click', '.pager', function (e) {
        var type = $(e.target).parent().data('type');
        var index = parseInt($(this).data('index'));
        var total = $(this).parent().parent().children('.media').length;
        if ($(e.target).parent().hasClass('disabled')) return false;
        if (type === 'all') {
            $(this).children('li').addClass('disabled');
            $(this).parent().parent().children('.media').removeClass('hidden');
            $(this).parent().remove();
            return false;
        }
        if (type === 'prev') {
            index -= 5;
            if (index <= 0) index = 0;
        }
        if (type === 'next') {
            index += 5;
            if (index >= total) index -= 5;
        }
        $(this).data('index', index);
        if (index === 0) {
            $(this).children('li[data-type="prev"]').addClass('disabled');
        } else {
            $(this).children('li[data-type="prev"]').removeClass('disabled');
        }
        if (index + 5 >= total) {
            $(this).children('li[data-type="next"]').addClass('disabled');
        } else {
            $(this).children('li[data-type="next"]').removeClass('disabled');
        }
        $(this).parent().parent().children('.media').each(function (i, elem) {
            if (i < index || i >= index + 5) {
                $(elem).addClass('hidden');
            } else {
                $(elem).removeClass('hidden');
            }
        });
    });

    // 字母图像
    function generateAvatar(username) {
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        // 设置画布尺寸
        canvas.width = 200;
        canvas.height = 200;
        // 绘制背景
        context.fillStyle = '#f4f4f4';
        context.fillRect(0, 0, canvas.width, canvas.height);
        // 绘制头像形状
        context.beginPath();
        context.arc(canvas.width / 2, canvas.height / 2, 80, 0, Math.PI * 2);
        context.closePath();
        context.clip();
        // 绘制用户名首字母
        context.fillStyle = '#555555';
        context.font = '100px Arial';
        context.textAlign = 'center';
        context.textBaseline = 'middle';
        context.fillText(username.charAt(0).toUpperCase(), canvas.width / 2, canvas.height / 2);
        // 将生成的图像转为 base64 编码
        var base64Image = canvas.toDataURL();
        return base64Image;
    }
    if ($('.media .media-object.avatar').length) {
        $('.media .media-object.avatar').each(function () {
            if ($(this).attr('src').indexOf(_localize.site_url) == -1) {
                $(this).attr('src', generateAvatar($(this).attr('alt')));
            }
        });
    }

    // 侧栏分页
    $('.list-group').on('click', '.pager', function (e) {
        var type = $(e.target).parent().data('type');
        var index = parseInt($(this).data('index'));
        var total = $(this).parent().parent().children('a.list-group-item').length;
        if ($(e.target).parent().hasClass('disabled')) return false;
        if (type === 'all') {
            $(this).children('li').addClass('disabled');
            $(this).parent().parent().children('a.list-group-item').removeClass('hidden');
            $(this).parent().remove();
            return false;
        }
        if (type === 'prev') {
            index -= 10;
            if (index <= 0) index = 0;
        }
        if (type === 'next') {
            index += 10;
            if (index >= total) index -= 10;
        }
        $(this).data('index', index);
        if (index === 0) {
            $(this).children('li[data-type="prev"]').addClass('disabled');
        } else {
            $(this).children('li[data-type="prev"]').removeClass('disabled');
        }
        if (index + 10 >= total) {
            $(this).children('li[data-type="next"]').addClass('disabled');
        } else {
            $(this).children('li[data-type="next"]').removeClass('disabled');
        }
        $(this).parent().parent().children('a.list-group-item').each(function (i, elem) {
            if (i < index || i >= index + 10) {
                $(elem).addClass('hidden');
            } else {
                $(elem).removeClass('hidden');
            }
        });
    });

    // 模块跟随
    if ($("#panel-affix").length) {
        var affixOffset = $("#panel-affix").offset();
        var documentHeight = $(document).height();
        var sideBarHeight = $("#panel-affix").height();
        var affixTimer = null;
        $(window).scroll(function () {
            if (affixTimer) return;
            affixTimer = setTimeout(function () {
                if ($(window).scrollTop() > affixOffset.top) {
                    var newPosition = ($(window).scrollTop() - affixOffset.top) + 35;
                    var maxPosition = documentHeight - (sideBarHeight + affixOffset.top + 135);
                    $("#panel-affix").css('margin-top', newPosition > maxPosition ? maxPosition : newPosition);
                } else {
                    $("#panel-affix").css('margin-top', 0);
                };
                affixTimer = null;
            }, 300);
        });
    }

    // 图片懒加载
    var lazyTimer = null;
    lazyLoad();
    $(window).scroll(lazyLoad);
    function lazyLoad() {
        if (lazyTimer) return false;
        var wHeight = $(window).innerHeight();
        lazyTimer = setTimeout(function () {
            $('img').each(function (i, elem) {
                if ($('html, body').scrollTop() + wHeight > $(elem).offset().top) {
                    if ($(elem).attr('src').match(/^data:image/) && $(elem).data('src') && $(elem).data('src').match(/\./)) {
                        $(elem).prop('src', $(elem).data('src'));
                    }
                }
            });
            lazyTimer = null;
        }, 500);
    }

    // 回顶与播放
    $('body').append('<div class="fixed-bottom"><div class="play-btn' + (_localize.voice_read == '0' || _localize.article_id == '0' ? ' hidden' : '') + '" title="' + _localize.audio_play + '"><span class="glyphicon glyphicon-play" aria-hidden="true"></span></div><div class="back-top" style="margin-top:3px" title="' + _localize.back_top + '"><span class="glyphicon glyphicon-menu-up" aria-hidden="true"></span></div></div>');
    $('body .fixed-bottom').css({
        position: 'fixed',
        right: 'calc(' + ($(window).width() > 1280 ? ($(window).width() - $('.container').outerWidth()) / 2 : 50) + 'px - 40px)',
        bottom: '30px',
        width: '40px',
        textAlign: 'center',
        color: '#fff',
        cursor: 'pointer',
        zIndex: 10,
        display: 'none'
    });
    $('body .fixed-bottom .play-btn, body .fixed-bottom .pause-btn, body .fixed-bottom .back-top').css({
        height: '40px',
        lineHeight: '40px',
        background: 'rgba(0,0,0,.3)',
        borderRadius: '50%'
    });
    $('body .fixed-bottom').on('click', '.play-btn, .resume-btn', function () {
        if ($('.btn-group .btn-resume').length) {
            $('.btn-group .btn-resume').click();
        } else {
            $('.btn-group .btn-play').click();
        }
    });
    $('body .fixed-bottom').on('click', '.pause-btn', function () {
        $('.btn-group .btn-pause').click();
    });
    $('body .fixed-bottom').on('click', '.back-top', function () {
        $('html, body').stop().animate({
            scrollTop: 0
        });
    });
    var scrollTimer = null;
    $(window).scroll(function () {
        if (scrollTimer) return;
        scrollTimer = setTimeout(function () {
            if ($(this).scrollTop() > 300) {
                $('body .fixed-bottom').css('display', 'block');
            } else {
                $('body .fixed-bottom').css('display', 'none');
            }
            scrollTimer = null;
        }, 300);
    });

    // 简繁转换
    if (_localize.lang === 'zh-TW') {
        var s = document.createElement('script');
        document.getElementsByTagName('head')[0].appendChild(s);
        s.type = 'text/javascript';
        s.src = _localize.site_url + '/static/js/zh-tranTW.js';
    }

    // 梅泰语（曼尼普尔语）
    if (_localize.lang === 'mni-Mtei') {
        var s = document.createElement('link');
        document.getElementsByTagName('head')[0].appendChild(s);
        s.rel = 'stylesheet';
        s.href = _localize.site_url + '/static/css/meetei-mayek.css';
    }

    // 谷歌tk算法
    function getTk(a) {
        var tkk = '406398.2087938574', e = tkk.split('.'), h = Number(e[0]) || 0, g = [], d = 0, i, j;
        for (var f = 0; f < a.length; f++) {
            var c = a.charCodeAt(f);
            128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ? (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240, g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)
        }
        a = h;
        for (var d = 0; d < g.length; d++) {
            a += g[d];
            i = '+-a^+6';
            for (var k = 0; k < i.length - 2; k += 3) {
                j = i.charAt(k + 2);
                j = 'a' <= j ? j.charCodeAt(0) - 87 : Number(j);
                j = '+' == i.charAt(k + 1) ? a >>> j : a << j;
                a = '+' == i.charAt(k) ? a + j & 4294967295 : a ^ j;
            }
        }
        i = '+-3^+b+-f';
        for (var k = 0; k < i.length - 2; k += 3) {
            j = i.charAt(k + 2);
            j = 'a' <= j ? j.charCodeAt(0) - 87 : Number(j);
            j = '+' == i.charAt(k + 1) ? a >>> j : a << j;
            a = '+' == i.charAt(k) ? a + j & 4294967295 : a ^ j;
        }
        a ^= Number(e[1]) || 0;
        0 > a && (a = (a & 2147483647) + 2147483648);
        a %= 1E6;
        return a.toString() + '.' + (a ^ h);
    }

    // Cookie操作
    function setCookie(name, value, options) {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            // use expires attribute, max-age is not supported by IE
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        var c = [name, '=', encodeURIComponent(value)].join('');
        var cookie = [c, expires, path, domain, secure].join('');
        document.cookie = cookie;
    }
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 社会化分享
    if ($('.entry-content').length) {
        window.socialShare && window.socialShare('#social-share');
    }
});
